package com.tqyan.service.chat.impl.novel;

import com.tqyan.dal.mapper.NovelMapper;
import com.tqyan.dal.mapper.NovelSceneMapper;
import com.tqyan.model.dto.*;
import com.tqyan.service.chat.AbstractChatPointService;
import com.tqyan.service.chat.ChatPointContent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @description 查看小说
 * <p> <功能详细描述> </p>
 *
 * @author 陈晨
 * @date 2023/6/13 17:36
 */
@Service
@Slf4j
public class NovelViewChatPointService extends AbstractChatPointService {

    @Autowired
    private NovelMapper novelMapper;
    @Autowired
    private NovelSceneMapper novelSceneMapper;

    @Override
    public String getPoint() {
        return ChatPointContent.NOVEL_VIEW;
    }

    @Override
    public ChatContentDTO chatPoint(UserDTO user, UserSettingDTO userSetting, ChatDTO chat, String content) {
        // 1, 获取小说标题
        content = content.replaceAll("：", ":");
        String title = null;
        if (content.split(":").length >= 2) {
            title = content.split(":")[1].trim();
        }

        String result;
        // 2.1, 无标题: 查询全部小说
        if (StringUtils.isBlank(title)) {
            List<NovelDTO> novelList = novelMapper.queryByUser(user.getId());
            if (CollectionUtils.isEmpty(novelList)) {
                result = ChatPointContent.ANSWER_1009;
            } else {
                String[] btns = new String[novelList.size()];
                for (int i = 0; i < novelList.size(); i++) {
                    NovelDTO novel = novelList.get(i);
                    if (null == novel) {
                        continue;
                    }
                    btns[i] = String.format(ChatPointContent.BTN_AUTO_TRUE
                            , ChatPointContent.NOVEL_VIEW + "：" + novel.getTitle()
                            , "《" + novel.getTitle() + "》");
                }
                result = ChatPointContent.generateButtonResult(ChatPointContent.ANSWER_1007, btns);
            }
        } else {
            // 3.1, 有标题: 查询标题是否存在
            NovelDTO novel = novelMapper.queryByTitle(user.getId(), title);
            // 3.2, 标题不存在: 提示、写
            if (null == novel) {
                result = String.format(ChatPointContent.ANSWER_1008, title, title);
            } else {
                // 3.3, 标题存在: 展示最后一个场景
                NovelSceneDTO novelSceneLast = novelSceneMapper.queryLastByNovel(user.getId(), novel.getId());
                // 场景不存在, 选择类型
                if (null == novelSceneLast) {
                    result = String.format(ChatPointContent.ANSWER_1006
                            , title, title
                            , title, title
                            , title, title
                            , title, title
                            , title, title
                            , title, title
                            , title, title
                            , title, title
                            , title);
                } else {
                    // 3.4, 追加文件
                    result = this.generateFileContent(novel, novelSceneLast);
                }
            }
        }
        if (StringUtils.isBlank(result)) {
            return null;
        }
        // 记录对话
        ChatContentDTO question = super.createQuestion(user, userSetting, chat, content, null, result);
        ChatContentDTO answer = super.createAnswer(userSetting, question, result);
        log.info("[{}] userId={}, content={}, 查看小说信息, 对话入库", this.getPoint(), user.getId(), content);
        return answer;
    }

    /**
     * @description 生成查看内容
     * <p> <功能详细描述> </p>
     *
     * @author 陈晨
     * @date 2023/6/16 16:09
     */
    public String generateViewContent(NovelDTO novel, NovelSceneDTO novelSceneLast) {
        StringBuilder result = new StringBuilder();
        result.append("《").append(novel.getTitle()).append("》\n\n");
        result.append("......\n\n");
        result.append(novelSceneLast.getContent()).append("\n");
        // 下一幕
        if (StringUtils.isBlank(novelSceneLast.getNextOption())) {
            return String.format(ChatPointContent.ANSWER_1010, novel.getTitle(), result);
        }
        // 下一场景
        String[] nextOptions = novelSceneLast.getNextOption().split("\n");
        String[] btns = new String[nextOptions.length];
        for (int i = 0; i < nextOptions.length; i++) {
            if (StringUtils.isBlank(nextOptions[i])) {
                continue;
            }
            btns[i] = String.format(
                    ChatPointContent.BTN_AUTO_TRUE
                    , ChatPointContent.NOVEL_NEXT_SCENE + ":" + novel.getTitle() + "_" + nextOptions[i]
                    , nextOptions[i]);
        }
        return ChatPointContent.generateButtonResult(result.toString(), btns);
    }

    /**
     * @description 生成文件内容
     * <p> <功能详细描述> </p>
     *
     * @author 陈晨
     * @date 2023/6/20 16:48
     */
    public String generateFileContent(NovelDTO novel, NovelSceneDTO novelSceneLast) {
        String fileName = novel.getTitle();
        if (fileName.length() > 11) {
            fileName = fileName.substring(0, 8) + "...";
        }
        return ChatPointContent.generateFileResult(
                this.generateViewContent(novel, novelSceneLast)
                , fileName
                , fileUrl + "novel/download/" + URLEncoder.encode(novel.getFileName(), StandardCharsets.UTF_8));
    }

}


